//
//  MediaEditPreviewCell.m
//  XPhoto
//
//  Created by baboy on 2019/5/6.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "MediaEditPhotoCell.h"
#import "BKImageView.h"
#import "PHAsset+x.h"
#import "PhotoAsset.h"
#import "NSDate+x.h"
#import <BKKit/UIImage+x.h>

#define NUM_PHOTO_OF_ROW    4
#define PHOTO_ITEM_MARGIN   5
#define PHOTO_ITEM_OFFSET_Y_TOP   5
#define PHOTO_ITEM_OFFSET_Y_BOTTOM   20
#define PHOTO_ITEM_OFFSET_X   20

@interface MediaEditPhotoCell()
@property(nonatomic, strong) NSMutableArray *photoViews;
+ (CGFloat)photoWidthForCellWidth:(CGFloat)width;
@end

@implementation MediaEditPhotoCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    if (!_photos) {
        _photos = [NSMutableArray array];
    }
    if(!_photoViews){
        _photoViews = [NSMutableArray array];
    }
}
- (void)layoutSubviews{
    [super layoutSubviews];
    for (NSInteger i = 0, n = self.photoViews.count; i < n; i++) {
        UIImageView *itemView = [self.photoViews objectAtIndex:i];
        CGRect itemFrame = [self itemFrameAtIndex:i];
        [UIView animateWithDuration:0.2 animations:^{
            itemView.frame = itemFrame;
        }];
    }
    [UIView animateWithDuration:0.2 animations:^{
        CGRect itemFrame = [self itemFrameAtIndex:self.photoViews.count];
        self.addButton.frame = itemFrame;
    }];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}
- (void)setShouldTakePhoto:(BOOL)shouldTakePhoto{
    _shouldTakePhoto = shouldTakePhoto;
    self.addButton.hidden = !shouldTakePhoto;
}
- (CGRect)itemFrameAtIndex:(NSInteger)index{
    CGFloat photoWidth = [MediaEditPhotoCell photoWidthForCellWidth:self.bounds.size.width];
    
    NSInteger row = index/NUM_PHOTO_OF_ROW;
    NSInteger col = index%NUM_PHOTO_OF_ROW;
    CGFloat x = col*(photoWidth+PHOTO_ITEM_MARGIN) + PHOTO_ITEM_OFFSET_X;
    CGFloat y = row*(photoWidth+PHOTO_ITEM_MARGIN) + PHOTO_ITEM_OFFSET_Y_TOP;
    CGRect itemFrame = CGRectMake(x, y, photoWidth, photoWidth);
    return itemFrame;
}
- (UIImageView *)createItemViewWithPhotoAsset:(PhotoAsset *)photoAsset atIndex:(NSInteger)index{
    CGRect itemFrame = [self itemFrameAtIndex:index];
    BKImageView *imageView = [[BKImageView alloc] initWithFrame: itemFrame];
    imageView.tag = index;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [imageView addTarget:self action:@selector(clickPhotoView:)];
    if (photoAsset.thumbImage) {
        imageView.image = photoAsset.thumbImage;
    }
    if (!photoAsset.thumbImage) {
        //显示图片
        dispatch_async(dispatch_get_main_queue(), ^{
            if (photoAsset.type == PhotoAssetTypeVideo) {
                [photoAsset.asset requestImageWithResultHandler:^(UIImage * _Nonnull image) {
                    photoAsset.thumbImage = image;
                    imageView.image = image;
                    NSString *fn = PHOTO_RANDOM_FILE_NAME(@"png");
                    NSString *fp = PHOTO_CACHE_FILE(fn);
                    NSData *imageData = UIImagePNGRepresentation(image);
                    BOOL t = [imageData writeToFile:fp atomically:YES];
                    DLOG(@"===fp:%@,%@,file_len:%ld,status:%d", fp,image,imageData.length,t);
                    if (t) {
                        photoAsset.thumbPath = fp;
                    }
                }];
            }
            if (photoAsset.type == PhotoAssetTypePhoto) {
                
                UIImage *originImage = [UIImage imageWithContentsOfFile:photoAsset.originPath];
                
                UIImage *thumbImage = [originImage cropAndScaleToSize:itemFrame.size];
                photoAsset.thumbImage = thumbImage;
                imageView.image = thumbImage;
            }
        });
        
    }
    return imageView;
}
- (void)setPhotos:(NSMutableArray *)photos{
    [self.photoViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.photoViews removeAllObjects];
    [self.photos removeAllObjects];
    [self addPhotos:photos];
}
- (void)addPhotos:(NSArray*)photos{
    for (NSInteger i = 0; i < photos.count; i++) {
        PhotoAsset *photoAsset = [photos objectAtIndex:i];
        UIImageView *itemView = [self createItemViewWithPhotoAsset:photoAsset atIndex:self.photos.count];
        [self.contentView addSubview:itemView];
        [self.photoViews addObject:itemView];
        [self.photos addObject:photoAsset];
    }
    [self setNeedsLayout];
}
- (void)removePhoto:(PhotoAsset*)removedAsset{
    for (int i = 0; i<self.photos.count; i++) {
        PhotoAsset *photoAsset = [self.photos objectAtIndex:i];
        if ([photoAsset.asset.localIdentifier isEqualToString:removedAsset.asset.localIdentifier]) {
            [self.photos removeObjectAtIndex:i];
            UIImageView *itemView = [self.photoViews objectAtIndex:i];
            [itemView removeFromSuperview];
            [self.photoViews removeObjectAtIndex:i];
            [self setNeedsLayout];
            break;
        }
    }
    
}
- (IBAction)clickAddPhotoButton:(id)btn{
    DLOG(@"clickAddPhotoButton");
    if (self.delegate && [self.delegate respondsToSelector:@selector(previewCell:addPhoto:)]) {
        [self.delegate previewCell:self addPhoto:btn];
    }
}
- (void)clickPhotoView:(id)photoView{
    if (self.delegate && [self.delegate respondsToSelector:@selector(previewCell:clickPhotoView:)]) {
        [self.delegate previewCell:self clickPhotoView:photoView];
    }
}
+ (CGFloat)photoWidthForCellWidth:(CGFloat)width{
    CGFloat photoWidth = ( width - (NUM_PHOTO_OF_ROW-1) * PHOTO_ITEM_MARGIN - 2*PHOTO_ITEM_OFFSET_X )/NUM_PHOTO_OF_ROW;
    return photoWidth;
}
+ (CGFloat)heightWithPhotos:(nullable NSArray*)photos cellWidth:(CGFloat)width shouldTakePhoto:(BOOL)shouldTakePhoto{
    NSInteger n = ( photos ? [photos count] : 0 ) + (shouldTakePhoto?1:0);
    NSInteger nRows = (n + NUM_PHOTO_OF_ROW -1) / NUM_PHOTO_OF_ROW;
    CGFloat photoWidth = [self photoWidthForCellWidth:width];
    CGFloat h = photoWidth * nRows + PHOTO_ITEM_MARGIN * (nRows-1) + PHOTO_ITEM_OFFSET_Y_TOP + PHOTO_ITEM_OFFSET_Y_BOTTOM;
    return h;
}
@end
